package com.gouying.web.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.gouying.common.utils.R;
import com.gouying.to.mq.SeckillOrderTo;
import com.gouying.vo.MemberResponseVo;
import com.gouying.web.feign.CouponFeignService;
import com.gouying.web.feign.ProductFeignService;
import com.gouying.web.interceptor.LoginUserInterceptor;
import com.gouying.web.service.SeckillService;
import com.gouying.web.to.SecKillSkuRedisTo;
import com.gouying.web.vo.SecKillSessionsWithSkus;
import com.gouying.web.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author ly
 */
@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    RedissonClient redissonClient;

    /**
     * 活动信息缓存前缀 保存所有的    key:seckill:sessions:start_end value:场次_sku
     */
    private final String SESSION_CACHE_PREFIX = "seckill:sessions:";

    /**
     * 商品信息缓存前缀
     */
    private final String SKU_KILL_CACHE_PREFIX = "seckill:skus:";

    /**
     * 商品库存信号量  +商品随机码
     */
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";


    @Override
    public void uploadSecKillSkuLatest3Days() {
        //1、去扫描最近三天需要参与秒杀的活动和商品
        R session = couponFeignService.getLatest3DaySession();
        if (session.getCode() == 0) {
            List<SecKillSessionsWithSkus> sessionData = session.getData(new TypeReference<List<SecKillSessionsWithSkus>>() {
            });
            //缓存活动信息和商品信息到redis中
            saveSessionInfos(sessionData);
            saveSessionSkuInfos(sessionData);
        }
    }

    public List<SecKillSkuRedisTo> blockHandler() {
        log.error("原方法getCurrentSeckillSkusResource被降级了……");
        return null;
    }

    /**
     * 返回当前时间可以参与秒杀的商品信息
     * blockHandler方法被限流后调用哪个方法
     *
     * @return
     */
    @SentinelResource(value = "getCurrentSeckillSkusResource", blockHandler = "blockHandler")
    @Override
    public List<SecKillSkuRedisTo> getCurrentSeckillSkus() {
        //1、确定当前时间属于哪个秒杀场次
        //1970-
        long time = System.currentTimeMillis();
        //自定义保护资源名，可以对她进行熔断降级
        try (Entry entry = SphU.entry("seckillSkus")) {
            //获取所有场次进行判断
            Set<String> keys = redisTemplate.keys(SESSION_CACHE_PREFIX + "*");
            for (String key : keys) {
                //把从redis中拿出来的数据格式化一下
                String replace = key.replace(SESSION_CACHE_PREFIX, "");
                String[] s = replace.split("_");
                //第一位是开始时间，第二位是结束时间
                long start = Long.parseLong(s[0]);
                long end = Long.parseLong(s[1]);
                //如果现在时间在开始和结束时间段内，那么就是我们要的当前场次
                if (time >= start && time <= end) {
                    //2、获取活动信息中的所有商品id  range = 场次ID_skuId
                    List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                    //3、根据从活动信息获取的商品id去获取商品详细信息
                    BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKU_KILL_CACHE_PREFIX);
                    List<String> list = hashOps.multiGet(range);
                    if (list != null) {
                        //将从redis获取的商品信息从json转为SecKillSkuRedisTo实体
                        //当前秒杀已经开始就需要随机码
                        return list.stream().map(item -> JSON.parseObject(item, SecKillSkuRedisTo.class)).collect(Collectors.toList());
                    }
                    break;
                }
            }
        } catch (BlockException e) {
            log.info("资源secKillSkus被限流，{}", e.getMessage());
        }
        return null;
    }

    /**
     * 获取某个商品的秒杀预告信息
     *
     * @param skuId
     * @return
     */
    @Override
    public SecKillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        //1、找到所有需要参与秒杀的商品的key
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKU_KILL_CACHE_PREFIX);
        //获取redis中所有key
        Set<String> keys = hashOps.keys();
        if (keys != null && keys.size() > 0) {
            //正则匹配key中（6_4）是否包含本商品id（无论是最近三天的第几场）
            String regx = "\\d_" + skuId;
            for (String key : keys) {
                //如果正则匹配，就获取这条信息
                if (Pattern.matches(regx, key)) {
                    String json = hashOps.get(key);
                    SecKillSkuRedisTo skuRedisTo = JSON.parseObject(json, SecKillSkuRedisTo.class);
                    //根据当前商品是否在秒杀时间内，来决定是否抹除随机码
                    long current = System.currentTimeMillis();
                    if (current >= skuRedisTo.getStartTime() && current <= skuRedisTo.getEndTime()) {
                        //在秒杀时间内
                    } else {
                        //不在秒杀时间内就抹除随机码
                        skuRedisTo.setRandomCode(null);
                    }
                    return skuRedisTo;
                }
            }
        }
        return null;
    }

    //TODO 完善：上架秒杀商品的时候，每一个数据都有过期时间
    //TODO       秒杀后续的流程，简化了收货地址等信息，包括秒杀请求部分非重要字段未设置封装

    /**
     * 真正的秒杀逻辑
     *
     * @param killId
     * @param key
     * @param num
     * @return
     */
    @Override
    public String kill(String killId, String key, Integer num) {
        long s1 = System.currentTimeMillis();
        MemberResponseVo respVo = LoginUserInterceptor.loginUser.get();
        //1、获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKU_KILL_CACHE_PREFIX);
        String json = hashOps.get(killId);
        //如果从redis中拿到的数据为空（这个数据不存在）
        if (StringUtils.isEmpty(json)) {
            return null;
        } else {
            //将从redis中拿到的秒杀信息转为实体
            SecKillSkuRedisTo redis = JSON.parseObject(json, SecKillSkuRedisTo.class);
            //校验前端请求发来的数据合法性
            Long startTime = redis.getStartTime();
            Long endTime = redis.getEndTime();
            long time = System.currentTimeMillis();
            //计算秒杀距离现在还有多久结束
            long ttl = endTime - time;
            //1、校验时间的合法性
            if (time >= startTime && time <= endTime) {
                //2、校验随机码和商品id
                String randomCode = redis.getRandomCode();
                String skuId = redis.getPromotionSessionId() + "_" + redis.getSkuId();
                if (randomCode.equals(key) && killId.equals(skuId)) {
                    //3、验证购物数量是否合理
                    if (num <= redis.getSecKillLimit()) {
                        //4、验证这个人是否已经购买过。幂等性：只要秒杀成功，就去占位。
                        //userId_sessionId_skuId作为唯一标识
                        String redisKey = respVo.getId() + "_" + skuId;
                        //该用户买过后做标记,并且这场活动结束后，标记就过期，不影响秒杀其他场次
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (aBoolean) {
                            //占位成功说明从来没有买过,开始秒杀（信号量）
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                            boolean b = semaphore.tryAcquire(num);
                            //获取信号量成功，才进入秒杀环节
                            if (b) {
                                String timeId = IdWorker.getTimeId();
                                //设置要发送消息的商品有关内容
                                SeckillOrderTo orderTo = new SeckillOrderTo();
                                orderTo.setOrederSn(timeId);
                                orderTo.setMemberId(respVo.getId());
                                orderTo.setNum(num);
                                orderTo.setPromotionSessionId(redis.getPromotionSessionId());
                                orderTo.setSkuId(redis.getSkuId());
                                orderTo.setSeckillPrice(redis.getSecKillPrice());
                                //秒杀成功，快速下单，发送MQ消息
                                rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", orderTo);
                                long s2 = System.currentTimeMillis();
                                log.info("秒杀耗时……{}", (s2 - s1));
                                return timeId;
                            }
                            return null;
                        } else {
                            //说明已经买过了，就不能再买了
                            return null;
                        }
                    }
                } else {
                    return null;
                }
            } else {
                return null;
            }
        }
        return null;
    }

    /**
     * 保存秒杀活动信息
     *
     * @param sessions
     */
    private void saveSessionInfos(List<SecKillSessionsWithSkus> sessions) {
        if (sessions != null) {
            sessions.forEach(session -> {
                long startTime = session.getStartTime().getTime();
                long endTime = session.getEndTime().getTime();
                //作为缓存redis的key seckill:sessions:
                String key = SESSION_CACHE_PREFIX + startTime + "_" + endTime;
                //先看redis中缓存过了没
                Boolean hasKey = redisTemplate.hasKey(key);
                //如果没有，再缓存活动信息
                if (!hasKey) {
                    //获取要缓存的活动信息的value（活动场次id_商品id）
                    List<String> collect = session.getRelationSkus().stream().map(item ->
                            item.getPromotionSessionId() + "_" + item.getSkuId().toString()).collect(Collectors.toList());
                    //redis缓存活动信息
                    redisTemplate.opsForList().leftPushAll(key, collect);
                }
            });
        }
    }

    /**
     * 保存秒杀商品信息
     *
     * @param sessions
     */
    private void saveSessionSkuInfos(List<SecKillSessionsWithSkus> sessions) {
        if (sessions != null) {
            sessions.forEach(session -> {
                //准备hash操作  seckill:skus:
                BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKU_KILL_CACHE_PREFIX);
                session.getRelationSkus().forEach(secKillSkuVo -> {
                    //4、随机码？ secKill?skuId=1&&key=xxxxxxxxx
                    String token = UUID.randomUUID().toString().replace("-", "");

                    //如果缓存中不存在要上架的商品，才进行缓存秒杀商品
                    if (!ops.hasKey(secKillSkuVo.getPromotionSessionId().toString() + "_" + secKillSkuVo.getSkuId().toString())) {
                        //缓存商品
                        SecKillSkuRedisTo redisTo = new SecKillSkuRedisTo();
                        //1、sku的基本数据信息
                        R skuInfo = productFeignService.getSkuInfo(secKillSkuVo.getSkuId());
                        if (skuInfo.getCode() == 0) {
                            SkuInfoVo info = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                            });
                            redisTo.setSkuInfo(info);
                        }
                        //2、从SecKillSessionsWithSkus拷贝每一个sku的秒杀信息
                        BeanUtils.copyProperties(secKillSkuVo, redisTo);
                        //3、设置当前商品秒杀的时间信息
                        redisTo.setStartTime(session.getStartTime().getTime());
                        redisTo.setEndTime(session.getEndTime().getTime());
                        redisTo.setRandomCode(token);

                        //转化为json存储
                        String jsonString = JSON.toJSONString(redisTo);
                        //向redis放数据 //获取要缓存的商品信息的value（活动场次id_商品id）
                        ops.put(secKillSkuVo.getPromotionSessionId().toString() + "_" + secKillSkuVo.getSkuId().toString(), jsonString);
                        //如果当前这个场次的库存信息已经上架就不需要上架了
                        //5、引入分布式的信号量，商品可以秒杀的数量作为信号量 限流； seckill:stock:
                        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                        semaphore.trySetPermits(secKillSkuVo.getSecKillCount());
                    }
                });
            });
        }
    }
}
